﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.ServiceModel;
using System.IO.IsolatedStorage;
//using Microsoft.Xna.Framework;
//using Microsoft.Xna.Framework.GamerServices;
using DataBasetestApp.ServiceReference2;

namespace DataBasetestApp
{
    public partial class MainPage : PhoneApplicationPage
    {
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            //CheckForMatch();
            this.Loaded += new RoutedEventHandler(MainPage_loaded);
        }

        // Method used to contact the database and fill the screen with the list of matches that are currently taking place
        void FillList()
        {
            try
            {
                LoadingBlock.Visibility = Visibility.Visible;
                this.progressBar1.IsIndeterminate = true;
                GAALiveServiceClient client = new GAALiveServiceClient();
                client.SearchListCompleted +=
                    new EventHandler<SearchListCompletedEventArgs>(client_SearchListCompleted);
                client.SearchListAsync();
            }
            catch (Exception e)
            {
                MessageBoxResult n = MessageBox.Show(e.Message);
            }
        }

        // Refresh button, reloads the list of matches
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            FillList();
        }

        // This happens when the main page opens. It loads the list of matches
        void MainPage_loaded(object sender, RoutedEventArgs e)
        {
            FillList();

        }

        void client_SearchListCompleted(object sender, SearchListCompletedEventArgs s)
        {
            if (s.Error == null)
            {
                lst.ItemsSource = s.Result;
                this.progressBar1.IsIndeterminate = false;
                LoadingBlock.Visibility = Visibility.Collapsed;
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (settings.Contains("matchStartedButNotFinished"))
            {
                if ((bool)settings["matchStartedButNotFinished"] == true)
                {
                    MessageBoxResult m = MessageBox.Show("You have already started another match." + Environment.NewLine + "Would you like to continue to report on this match?", "Return to Match", MessageBoxButton.OKCancel);

                    // if you choose OK on the message box, you will be directed to the match update page where you can keep track of the match you are currently watching
                    if (m == MessageBoxResult.OK)
                    {
                        //Uri uri = new Uri("/Views/MatchUpdatePage.xaml");
                        NavigationService.Navigate(new Uri("/Views/MatchUpdatePage.xaml", UriKind.Relative));
                    }

                    // If you choose Cancel on the message box, you will delete the match that is already taking place, and will be brought to a new match creation page
                    if (m == MessageBoxResult.Cancel)
                    {
                        MessageBoxResult n = MessageBox.Show("This will begin a new match and dispose of the match you were reporting on." + Environment.NewLine + "Is that ok?", "Dispose of Match", MessageBoxButton.OKCancel);

                        if (n == MessageBoxResult.OK)
                        {
                            int id = (int)settings["ID"];
                            settings["matchStartedButNotFinished"] = false;
                            settings["matchOver"] = true;

                            GAALiveServiceClient client = new GAALiveServiceClient();
                            client.DeleteMatchCompleted +=
                                new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_DeleteMatchCompleted);
                            client.DeleteMatchAsync(id);
                        }
                    }
                }
                else
                {
                    // Navigate to the match creation page
                    NavigationService.Navigate(new Uri("/Views/LoginPage.xaml", UriKind.Relative));
                }
            }
            else
            {
                // Navigate to the match creation page
                NavigationService.Navigate(new Uri("/Views/LoginPage.xaml", UriKind.Relative));
            }
        }

        // Navigate to the details page for this match when the match is selected in the list
        private void lst_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                var selectedItem = (Match)e.AddedItems[0];
                int ID;
                int userID = 0;
                string HomeTeam, Awayteam, Score, Time, Location, Competition;
                ID = selectedItem.Match_ID;
                HomeTeam = selectedItem.HomeTeam;
                Awayteam = selectedItem.AwayTeam;
                if (selectedItem.User_ID != null)
                {
                    userID = (int)selectedItem.User_ID;
                }
                //userID = (int)selectedItem.User_ID;
                Score = selectedItem.Score;
                Location = selectedItem.Location;
                Competition = selectedItem.Competition;
                Time = selectedItem.Time;
                //string temp = userID.ToString();
                string UserID = userID.ToString();
                NavigationService.Navigate(new Uri("/Views/MatchDetails.xaml?ID=" + ID + "&HomeTeam=" + HomeTeam + "&AwayTeam=" + Awayteam + "&Score=" + Score + "&Location=" + Location + "&Time=" + Time + "&Competition=" + Competition + "&UserID=" + UserID, UriKind.Relative));
                ((ListBox)sender).SelectedIndex = -1;
            }
        }

        // Delete all the settings from Isolated storage  so we can start from scratch again
        void client_DeleteMatchCompleted(object sender, EventArgs c)
        {
            settings.Remove("matchOver");
            settings.Remove("team1Goals");
            settings.Remove("team1points");
            settings.Remove("team2Goals");
            settings.Remove("team2Points");
            settings.Remove("homeTeam");
            settings.Remove("awayTeam");
            settings.Remove("ID");
            settings.Remove("minuteStarted");
            settings.Remove("mins");
            settings.Remove("time");
            NavigationService.Navigate(new Uri("/Views/LoginPage.xaml", UriKind.Relative));
        }

        // Navigate to the page containing Historical matches
        private void HistoricalButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/HistoricalMatches.xaml", UriKind.Relative));
        }
    }
}